/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package mathma.discrete.set.form;

import mathma.core.expr.Expression;

import mathma.core.form.MultiExpression;

import mathma.core.value.Value;

import mathma.discrete.set.Set;

import java.util.ArrayList;
import java.util.List;

/**
 * @since 0.2.2
 * @author Ethan Levine
 */
public class UnionExpression<E extends Value> extends MultiExpression<Set<E>, Set<E>> {

    public UnionExpression(Expression<Set<E>>... operands) {
        super(Set.GenericType, operands);
    }

    public UnionExpression(List<Expression<Set<E>>> operands) {
        super(Set.GenericType, operands);
    }

    public Set<E> evaluate() {
        List<Set<E>> values = new ArrayList<Set<E>>();
        for (Expression<Set<E>> expr : getOperands()) {
            values.add(expr.evaluate());
        }
        if (values.size() == 0) {
            // TODO - what to do for empty expressions?
            return null;
        } else {
            Set<E> union = null;
            for (Set<E> value : values) {
                if (union == null) {
                    union = value;
                } else {
                    union = union.union(value);
                }
            }
            return union;
        }
    }

    public UnionExpression newInstance(List<Expression<Set<E>>> operands) {
        return new UnionExpression(operands);
    }
}
